package api.cie.rss.dal;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * The class to manipulate with the Category table in the database
 * @author STL-API
 *
 */
public class CategoryDAL {

	public static final String KEY_TITLE = "title";
	public static final String KEY_ROWID = "_id";
	
	public static final String DATABASE_TABLE = "Category";
	private SQLiteDatabase database;
	
	public CategoryDAL(DatabaseAdapter dbAdapter) {
		database = dbAdapter.getDatabase();
	}
	
	/**
	 * Create a new Category. If the Category is successfully created, return the new
	 * rowId for that Category, otherwise return a -1 to indicate failure.
	 */
	public long createCategory(String title) {
		ContentValues initialValues = createContentValues(title);

		return database.insert(DATABASE_TABLE, null, initialValues);
	}
	
	private ContentValues createContentValues(String title) {
		ContentValues values = new ContentValues();
		values.put(KEY_TITLE, title);
		
		return values;
	}
	
	/**
	 * Deletes Category
	 */
	public boolean deleteCategory(long rowId) {
		return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all categories in the database
	 * 
	 * @return Cursor over all categories
	 */
	public Cursor fetchAllCategories() {
		return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_TITLE }, null, null, null,
				null, null);
	}

	/**
	 * Return a Cursor positioned at the defined Category
	 */
	public Cursor fetchCategory(long rowId) throws SQLException {
		Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID, KEY_TITLE },
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	/**
	 * Update a title category in the database
	 * @param key
	 * @param newValue
	 */
	public void updateCategory(long key, String newValue) {
		ContentValues values = new ContentValues();
		values.put(KEY_TITLE, newValue);
		database.update(DATABASE_TABLE, values, KEY_ROWID + " = " + key , null);
	}
}
